# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：attr操作的curd
"""
from schemas.attr import AttrAddSchemas, AttrOutSchemas, AttrEditSchemas
from models.base import Attribute, Category
from fastapi import HTTPException


async def attr_add_curd(post: AttrAddSchemas) -> AttrOutSchemas:
    if await Attribute.get_or_none(name=post.name):
        raise HTTPException(status_code=422, detail='属性名不能重复！')
    if post.cid_id:
        if not await Category.get_or_none(id=post.cid_id):
            raise HTTPException(status_code=422, detail='新增属性所属的分类id不存在！')

    attr = await Attribute.create(**post.dict(), _type=post.type)

    return AttrOutSchemas(**dict(attr), type=attr._type)


async def attr_edit_curd(post: AttrEditSchemas) -> AttrOutSchemas:
    attr = await Attribute.get_or_none(id=post.id)
    if not attr:
        raise HTTPException(status_code=422, detail='该商品属性不存在！')
    if post.type not in ['static', 'dynamic']:
        raise HTTPException(status_code=422, detail='商品属性类型只能是static或dynamic！')
    if attr.name != post.name and await Attribute.exists(name=post.name):
        raise HTTPException(status_code=422, detail='商品属性名称不能重复！')
    if post.cid_id:
        if not await Category.get_or_none(id=post.cid_id):
            raise HTTPException(status_code=422, detail='新增属性所属的分类id不存在！')
    # 更改自己身上的字段
    attr_dict = {
        'name': post.name,
        'val': post.val,
        '_type': post.type
    }
    await attr.update_from_dict(attr_dict)
    await attr.save()
    # 获取新的关联关系对象
    category = await Category.filter(id=post.cid_id).first()
    # 更新关联关系
    await Attribute.filter(id=post.id).update(cid=category)
    # 重新获取下新后的数据
    attr = await Attribute.get_or_none(id=post.id)
    return AttrOutSchemas(**dict(attr), type=attr._type)
